//package com.wlq.demo.uitls;
//
//
//
//import com.aspose.words.Document;
//import com.aspose.words.SaveFormat;
//import org.apache.pdfbox.pdfparser.PDFStreamParser;
//import org.apache.pdfbox.pdmodel.PDPage;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import java.io.*;
//
//import com.aspose.words.Document;
//import com.aspose.words.SaveFormat;
//import org.apache.pdfbox.Loader;
//import org.apache.pdfbox.contentstream.operator.Operator;
//import org.apache.pdfbox.cos.COSArray;
//import org.apache.pdfbox.cos.COSDictionary;
//import org.apache.pdfbox.cos.COSName;
//import org.apache.pdfbox.cos.COSString;
//import org.apache.pdfbox.pdfparser.PDFStreamParser;
//import org.apache.pdfbox.pdfwriter.ContentStreamWriter;
//import org.apache.pdfbox.pdmodel.PDDocument;
//import org.apache.pdfbox.pdmodel.PDPage;
//import org.apache.pdfbox.pdmodel.PDPageTree;
//import org.apache.pdfbox.pdmodel.PDResources;
//import org.apache.pdfbox.pdmodel.common.PDStream;
//
//import java.io.FileInputStream;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.Iterator;
//import java.util.List;
//
//// 格式大全:前缀对应以下方法的fmt值
//// 0:Microsoft Word 97 - 2003 文档 (.doc)
//// 1:Microsoft Word 97 - 2003 模板 (.dot)
//// 2:文本文档 (.txt)
//// 3:文本文档 (.txt)
//// 4:文本文档 (.txt)
//// 5:文本文档 (.txt)
//// 6:RTF 格式 (.rtf)
//// 7:文本文档 (.txt)
//// 8:HTML 文档 (.htm)(带文件夹)
//// 9:MHTML 文档 (.mht)(单文件)
//// 10:MHTML 文档 (.mht)(单文件)
//// 11:XML 文档 (.xml)
//// 12:Microsoft Word 文档 (.docx)
//// 13:Microsoft Word 启用宏的文档 (.docm)
//// 14:Microsoft Word 模板 (.dotx)
//// 15:Microsoft Word 启用宏的模板 (.dotm)
//// 16:Microsoft Word 文档 (.docx)
//// 17:PDF 文件 (.pdf)
//// 18:XPS 文档 (.xps)
//// 19:XML 文档 (.xml)
//// 20:XML 文档 (.xml)
//// 21:XML 文档 (.xml)
//// 22:XML 文档 (.xml)
//// 23:OpenDocument 文本 (.odt)
//// 24:WTF 文件 (.wtf)
//
//public class WordUtil {
//    private static final Logger logger = LoggerFactory.getLogger(WordUtil.class);
//    //doc格式
//    private static final int DOC_FMT = 0;
//    //docx格式
//    private static final int DOCX_FMT = 12;
//    //html格式
//    private static final int HTML_FMT = 8;
//
//    public static void main(String[] args) throws IOException {
//        String srcPath = "d:\\test\\1.docx";
////        setWordWaterMark(srcPath,"D:\\2121.docx","这是水印");
//        try {
//            InputStream in = new FileInputStream(new File(srcPath));
////            InputStream in2 = new FileInputStream(new File("d:\\test\\122.pdf"));
//
//            DocxToPdfConverter1(in);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//
//    }
//
//    public static void DocxToPdfConverter1(InputStream in){
//        long old = System.currentTimeMillis();
//        try {
//            //新建一个pdf文档
//            String pdfPath="D:\\test\\2121.pdf";
//            File file = new File(pdfPath);
//            FileOutputStream os = new FileOutputStream(file);
//            //Address是将要被转化的word文档
//            Document doc = new Document(in);
//            //全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
//            doc.save(os, SaveFormat.PDF);
//            os.close();
//            //去除水印
//            removeWatermark(new File(pdfPath));
//            //转化用时
//            long now = System.currentTimeMillis();
//            System.out.println("Word 转 Pdf 共耗时：" + ((now - old) / 1000.0) + "秒");
//        } catch (Exception e) {
//            System.out.println("Word 转 Pdf 失败...");
//            e.printStackTrace();
//        }
//    }
//
//    //替换pdf文本内容
//    public static void replaceText(PDPage page, String searchString, String replacement) throws IOException {
//        PDFStreamParser parser = new PDFStreamParser(page);
//        List<?> tokens = parser.parse();
//        for (int j = 0; j < tokens.size(); j++) {
//            Object next = tokens.get(j);
//            if (next instanceof Operator) {
//                Operator op = (Operator) next;
//                String pstring = "";
//                int prej = 0;
//                if (op.getName().equals("Tj")) {
//                    COSString previous = (COSString) tokens.get(j - 1);
//                    String string = previous.getString();
//                    string = string.replaceFirst(searchString, replacement);
//                    previous.setValue(string.getBytes());
//                } else if (op.getName().equals("TJ")) {
//                    COSArray previous = (COSArray) tokens.get(j - 1);
//                    for (int k = 0; k < previous.size(); k++) {
//                        Object arrElement = previous.getObject(k);
//                        if (arrElement instanceof COSString) {
//                            COSString cosString = (COSString) arrElement;
//                            String string = cosString.getString();
//
//                            if (j == prej) {
//                                pstring += string;
//                            } else {
//                                prej = j;
//                                pstring = string;
//                            }
//                        }
//                    }
//                    if (searchString.equals(pstring.trim())) {
//                        COSString cosString2 = (COSString) previous.getObject(0);
//                        cosString2.setValue(replacement.getBytes());
//                        int total = previous.size() - 1;
//                        for (int k = total; k > 0; k--) {
//                            previous.remove(k);
//                        }
//                    }
//                }
//            }
//        }
//        List<PDStream> contents = new ArrayList<>();
//        Iterator<PDStream> streams = page.getContentStreams();
//        while (streams.hasNext()) {
//            PDStream updatedStream = streams.next();
//            OutputStream out = updatedStream.createOutputStream(COSName.FLATE_DECODE);
//            ContentStreamWriter tokenWriter = new ContentStreamWriter(out);
//            tokenWriter.writeTokens(tokens);
//            contents.add(updatedStream);
//            out.close();
//        }
//        page.setContents(contents);
//    }
//
//    //移除图片水印
//    public static void removeImage(PDPage page, String cosName) {
//        PDResources resources = page.getResources();
//        COSDictionary dict1 = resources.getCOSObject();
//        resources.getXObjectNames().forEach(e -> {
//            if (resources.isImageXObject(e)) {
//                COSDictionary dict2 = dict1.getCOSDictionary(COSName.XOBJECT);
//                if (e.getName().equals(cosName)) {
//                    dict2.removeItem(e);
//                }
//            }
//            page.setResources(new PDResources(dict1));
//        });
//    }
//
//
//    //移除文字水印
//    public static boolean removeWatermark(File file) {
//        try {
//            //通过文件名加载文档
//            PDDocument document = Loader.loadPDF(file);
//            PDPageTree pages = document.getPages();
//            Iterator<PDPage> iter = pages.iterator();
//            while (iter.hasNext()) {
//                PDPage page = iter.next();
//                //去除文字水印
//                replaceText(page, "Evaluation Only. Created with Aspose.Words. Copyright 2003-2021 Aspose", "");
//                replaceText(page, "Pty Ltd.", "");
//                replaceText(page, "Created with an evaluation copy of Aspose.Words. To discover the full", "");
//                replaceText(page, "versions of our APIs please visit: https://products.aspose.com/words/", "");
//                replaceText(page, "This document was truncated here because it was created in the Evaluation", "");
//                //去除图片水印
//                removeImage(page, "X1");
//            }
//            document.removePage(document.getNumberOfPages() - 1);
//            file.delete();
//            document.save(file);
//            document.close();
//            return true;
//        } catch (IOException ex) {
//            ex.printStackTrace();
//            return false;
//        }
//
//    }
//
//
////    public static void WatermarkPDFAndSetPdfPassword(InputStream in) {
////
////
////        // 加载PDF文档
////        PDDocument document = null;
////        try {
////            document = PDDocument.load(in);
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
////
////        // 遍历每一页
////        for (PDPage page : document.getPages()) {
////            // 创建内容流以在页面上绘制文本
////            PDPageContentStream contentStream = null;
////            try {
////                contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);
////
////                // 设置字体、颜色和透明度
////                contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36);
////                contentStream.setNonStrokingColor(200, 200, 200); // 灰色
////                contentStream.setLineWidth(5);
////
////                // 计算水印位置（居中）
////                float x = page.getMediaBox().getWidth() / 2;
////                float y = page.getMediaBox().getHeight() / 2;
////
////                // 添加水印文本
////                contentStream.beginText();
////                contentStream.newLineAtOffset(x, y);
////                contentStream.showText("SUNTHER");
////                contentStream.endText();
////
////                // 关闭内容流并保存更改
////                contentStream.close();
////
////                //2、加密
////                // 创建访问权限对象
////                AccessPermission accessPermission = new AccessPermission();
////                accessPermission.setCanPrint(true);
////                accessPermission.setCanModify(false);
////                accessPermission.setCanFillInForm(false);
////                accessPermission.setCanExtractContent(false);
////
////                // 创建保护策略对象
////                StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy("password", "1234", accessPermission);
////
////                // 应用保护策略到文档
////                document.protect(protectionPolicy);
////
////                // 保存带有水印的PDF文档
////                document.save("output.pdf");
////
////                // 关闭文档
////                document.close();
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
////        }
////    }
//
////    public static void WatermarkPDF(InputStream in) {
////        // 加载PDF文档
////        PDDocument document = null;
////        try {
////            document = PDDocument.load(in);
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
////
////        // 遍历每一页
////        for (PDPage page : document.getPages()) {
////            // 创建内容流以在页面上绘制文本
////            PDPageContentStream contentStream = null;
////            try {
////                contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);
////
////                // 设置字体、颜色和透明度
////                contentStream.setFont(PDType1Font.HELVETICA_BOLD, 36);
////                contentStream.setNonStrokingColor(200, 200, 200); // 灰色
////                contentStream.setLineWidth(5);
////
////                // 计算水印位置（居中）
////                float x = page.getMediaBox().getWidth() / 2;
////                float y = page.getMediaBox().getHeight() / 2;
////
////                // 添加水印文本
////                contentStream.beginText();
////                contentStream.newLineAtOffset(x, y);
////                contentStream.showText("shuiying");
////                contentStream.endText();
////
////                // 关闭内容流并保存更改
////                contentStream.close();
////
////                // 保存带有水印的PDF文档
////                document.save("output.pdf");
////
////                // 关闭文档
////                document.close();
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
////        }
////    }
//
////    public static void SetPdfPassword (InputStream in){
////        try {
////            // 加载PDF文件
////            PDDocument document = PDDocument.load(in);
////
////            // 创建访问权限对象
////            AccessPermission accessPermission = new AccessPermission();
////            accessPermission.setCanPrint(true);
////            accessPermission.setCanModify(false);
////            accessPermission.setCanFillInForm(false);
////            accessPermission.setCanExtractContent(false);
////
////            // 创建保护策略对象
////            StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy("password", "123456", accessPermission);
////
////            // 应用保护策略到文档
////            document.protect(protectionPolicy);
////
//////            // 保存加密后的PDF文件
//////            document.save("output.pdf");
////
////            // 关闭文档
////            document.close();
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
////    }
//
////    public static void setPolicy(InputStream in) throws IOException {
////
////        Document document = new Document(in);
////
////        XWPFDocument doc= null;
////        try {
////            doc = new XWPFDocument(in);
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
////
////        //设置文档保护
//////        doc.enforceReadonlyProtection("123456",HashAlgorithm.sha512);
////
////        Biff8EncryptionKey.setCurrentUserPassword("123456");
////
////        // the body content
////        XWPFParagraph paragraph = doc.createParagraph();
////        XWPFRun run=paragraph.createRun();
//////        run.setText("The Body:");
////
////        // create header-footer
////        XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy();
////
////        if (headerFooterPolicy == null) headerFooterPolicy = doc.createHeaderFooterPolicy();
////
////        // 水印内容
////        headerFooterPolicy.createWatermark("这是水印");
////
////        // get the default header
////        // Note: createWatermark also sets FIRST and EVEN headers
////        // but this code does not updating those other headers
////        XWPFHeader header = headerFooterPolicy.getHeader(XWPFHeaderFooterPolicy.DEFAULT);
////        paragraph = header.getParagraphArray(0);
////
////        // get com.microsoft.schemas.vml.CTShape where fill color and rotation is set
////        org.apache.xmlbeans.XmlObject[] xmlobjects = paragraph.getCTP().getRArray(0).getPictArray(0).selectChildren(
////                new javax.xml.namespace.QName("urn:schemas-microsoft-com:vml", "shape"));
////
////        if (xmlobjects.length > 0) {
////            com.microsoft.schemas.vml.CTShape ctshape = (com.microsoft.schemas.vml.CTShape)xmlobjects[0];
////            // set fill color
////            ctshape.setFillcolor("#d8d8d8");
////            // set rotation
////            ctshape.setStyle(ctshape.getStyle() + ";rotation:315");
////            //System.out.println(ctshape);
////        }
////        //文件输出地址
////        FileOutputStream out = null;
////        try {
////            out = new FileOutputStream("D:\\2121.docx");
////        } catch (FileNotFoundException e) {
////            e.printStackTrace();
////        }
////        System.out.println("水印添加成功!");
////        try {
////            doc.write(out);
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
////        try {
////            out.close();
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
////        try {
////            doc.close();
////        } catch (IOException e) {
////            e.printStackTrace();
////        }
////    }
//
//
//    /**
//     * word文字水印
//     *
//     * @param inputPath
//     * @param outPath
//     * @param markStr
//     */
////    public static void setWordWaterMark(String inputPath, String outPath, String markStr) {
////        File inputFile = new File(inputPath);
////        //2003doc 用HWPFDocument  ； 2007doc 用 XWPFDocument
////        XWPFDocument doc = null;
////        try {
////            // 延迟解析比率
////            ZipSecureFile.setMinInflateRatio(-1.0d);
////            doc = new XWPFDocument(new FileInputStream(inputFile));
////        } catch (FileNotFoundException e) {
////        } catch (IOException e) {
////        } catch (Exception e) {
////        }
////        XWPFHeaderFooterPolicy headerFooterPolicy = doc.getHeaderFooterPolicy();
////        if (headerFooterPolicy == null) {
////            headerFooterPolicy = doc.createHeaderFooterPolicy();
////        }
////        //添加水印
////        headerFooterPolicy.createWatermark(markStr);
////        File file = new File(outPath);
////        if (!file.exists()) {
////            try {
////                file.createNewFile();
////            } catch (IOException e) {
////            }
////        }
////        OutputStream os = null;
////        try {
////            os = new FileOutputStream(outPath);
////            doc.write(os);
////        } catch (FileNotFoundException e) {
////        } catch (Exception e) {
////        } finally {
////            if (os != null) {
////                try {
////                    os.close();
////                } catch (IOException e) {
////                    e.printStackTrace();
////                }
////            }
////            if (doc != null) {
////                try {
////                    doc.close();
////                } catch (IOException e) {
////                    e.printStackTrace();
////                }
////            }
////        }
////    }
//}
